package com.ruoyi.ax.service.impl;

import java.util.Date;
import java.util.List;

import com.ruoyi.ax.domain.AxAccountChangeRecord;
import com.ruoyi.ax.service.IAxAccountChangeRecordService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.ApplyTypeEnum;
import com.ruoyi.common.enums.AuditStatus;
import com.ruoyi.common.enums.changeSouceType;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.ax.mapper.AxWithdrawalMapper;
import com.ruoyi.ax.domain.AxWithdrawal;
import com.ruoyi.ax.service.IAxWithdrawalService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 提现记录Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-05-19
 */
@Service
public class AxWithdrawalServiceImpl implements IAxWithdrawalService 
{
    @Autowired
    private AxWithdrawalMapper axWithdrawalMapper;

    @Autowired
    private ISysUserService userService;
    @Autowired
    private IAxAccountChangeRecordService axAccountChangeRecordService;
    /**
     * 查询提现记录
     * 
     * @param id 提现记录主键
     * @return 提现记录
     */
    @Override
    public AxWithdrawal selectAxWithdrawalById(Long id)
    {
        return axWithdrawalMapper.selectAxWithdrawalById(id);
    }

    /**
     * 查询提现记录列表
     * 
     * @param axWithdrawal 提现记录
     * @return 提现记录
     */
    @Override
    public List<AxWithdrawal> selectAxWithdrawalList(AxWithdrawal axWithdrawal)
    {
        List<AxWithdrawal> list = axWithdrawalMapper.selectAxWithdrawalList(axWithdrawal);
        for(AxWithdrawal axWithdrawal1:list){
            axWithdrawal1.setSysUser(userService.selectUserById(Long.valueOf(axWithdrawal1.getApplyer())));
        }
        return list;
    }

    /**
     * 新增提现记录
     * 
     * @param axWithdrawal 提现记录
     * @return 结果
     */
    @Override
    public int insertAxWithdrawal(AxWithdrawal axWithdrawal)
    {
        SysUser sysUser= userService.selectUserById(SecurityUtils.getUserId());
//        Double totalAbleCash=  Double.valueOf(sysUser.getRechargeAmount())+Double.valueOf(sysUser.getIndirectAbleCashIncome())+
//                Double.valueOf(sysUser.getAbleCashIncome());

        if(ApplyTypeEnum.充值金额.getCode().equals(axWithdrawal.getApplyType())){
            Double totalAbleCash=  Double.valueOf(sysUser.getRechargeAmount());
            if(Double.valueOf(axWithdrawal.getAmout())>totalAbleCash){
                throw  new GlobalException("余额不足");
            }
        }else if(ApplyTypeEnum.收益.getCode().equals(axWithdrawal.getApplyType())){
            Double totalAbleCash=  Double.valueOf(sysUser.getAbleCashIncome())+ Double.valueOf(sysUser.getIndirectAbleCashIncome());
            if(Double.valueOf(axWithdrawal.getAmout())>totalAbleCash){
                throw  new GlobalException("余额不足");
            }
        }
        AxWithdrawal axWithdrawalParam=new AxWithdrawal();
        axWithdrawalParam.setApplyer(SecurityUtils.getUserId()+"");
        axWithdrawalParam.setStatus("1");
        List<AxWithdrawal> list1= axWithdrawalMapper.selectAxWithdrawalList(axWithdrawalParam);
        if(list1.size()>0){
            throw  new GlobalException("正在处理中，请不要重复申请");
        }
        /////////////////
        axWithdrawal.setCommissionRate("7%");
        /////////////设置手续费
        Double commission= Double.valueOf(axWithdrawal.getAmout())*((7.0)/100.0);
        axWithdrawal.setCommission(String.format("%.2f", commission));

        axWithdrawal.setCreateTime(DateUtils.getNowDate());
        return axWithdrawalMapper.insertAxWithdrawal(axWithdrawal);
    }

    /**
     * 修改提现记录
     * 
     * @param axWithdrawal 提现记录
     * @return 结果
     */
    @Override
    public int updateAxWithdrawal(AxWithdrawal axWithdrawal)
    {
        axWithdrawal.setUpdateTime(DateUtils.getNowDate());
        return axWithdrawalMapper.updateAxWithdrawal(axWithdrawal);
    }

    @Override
    @Transactional
    public int auditAxWithdrawal(AxWithdrawal axWithdrawal) {

        if(AuditStatus.打款成功.getCode().equals(axWithdrawal.getStatus())){
            AxWithdrawal axWithdrawal1=axWithdrawalMapper.selectAxWithdrawalById(axWithdrawal.getId());
            String applyerId= axWithdrawal1.getApplyer();
            SysUser applyer=  userService.selectUserById(Long.valueOf(applyerId));

//            Double totalAbleCash=  Double.valueOf(applyer.getRechargeAmount())+Double.valueOf(applyer.getIndirectAbleCashIncome())+
//                    Double.valueOf(applyer.getAbleCashIncome());

            if(ApplyTypeEnum.充值金额.getCode().equals(axWithdrawal.getApplyType())){
                Double totalAbleCash=  Double.valueOf(applyer.getRechargeAmount());
                if(Double.valueOf(axWithdrawal1.getAmout())>totalAbleCash){
                    throw  new GlobalException("余额不足");
                }
            }else if(ApplyTypeEnum.收益.getCode().equals(axWithdrawal.getApplyType())){
                Double totalAbleCash=  Double.valueOf(applyer.getAbleCashIncome())+ Double.valueOf(applyer.getIndirectAbleCashIncome());
                if(Double.valueOf(axWithdrawal1.getAmout())>totalAbleCash){
                    throw  new GlobalException("余额不足");
                }
            }else{
                throw  new GlobalException("未检测到提现类型");
            }

            // 此处有个逻辑问题，充值金额和收益优先扣那个
            //开始扣减账户余额
            AxAccountChangeRecord axAccountChangeRecord=new AxAccountChangeRecord();
            axAccountChangeRecord.setOrderNumber(axWithdrawal1.getId()+"");
            axAccountChangeRecord.setOrderId(axWithdrawal1.getId()+"");
            axAccountChangeRecord.setSysuserId(Long.valueOf(axWithdrawal1.getApplyer()));

            if(ApplyTypeEnum.充值金额.getCode().equals(axWithdrawal.getApplyType())){
                Double remainRechargeAmount= Double.valueOf(applyer.getRechargeAmount()) - Double.valueOf(axWithdrawal1.getAmout());
                applyer.setRechargeAmount(String.format("%.2f",remainRechargeAmount));
                axAccountChangeRecord.setChangeSource(changeSouceType.提现.getCode());
                axAccountChangeRecord.setChangeSourceName(changeSouceType.提现.name());
                axAccountChangeRecord.setChangeAmount("-"+axWithdrawal1.getAmout());
                axAccountChangeRecordService.insertAxAccountChangeRecord(axAccountChangeRecord);
            }else{

                Double ableCashIncome=  Double.valueOf(applyer.getAbleCashIncome());

                if(Double.valueOf(axWithdrawal1.getAmout())>ableCashIncome){
                    //当拍品券不够时;先扣拍品券，再扣津贴券
                    axAccountChangeRecord.setChangeSource(changeSouceType.拍品券提现.getCode());
                    axAccountChangeRecord.setChangeSourceName(changeSouceType.拍品券提现.name());
                    axAccountChangeRecord.setChangeAmount("-"+ableCashIncome);
                    axAccountChangeRecordService.insertAxAccountChangeRecord(axAccountChangeRecord);
                    // 更新用户直接可提现金额
                    applyer.setAbleCashIncome("0.00");
                    // 间接受益扣减收益明细
                    Double deeIndirectAbleCashIncome=  Double.valueOf(axWithdrawal1.getAmout()) - ableCashIncome;
                    axAccountChangeRecord.setChangeSource(changeSouceType.津贴券提现.getCode());
                    axAccountChangeRecord.setChangeSourceName(changeSouceType.津贴券提现.name());
                    axAccountChangeRecord.setChangeAmount("-"+deeIndirectAbleCashIncome);
                    axAccountChangeRecordService.insertAxAccountChangeRecord(axAccountChangeRecord);
                    // 用户间接受益
                    Double  indirectAbleCashIncome=Double.valueOf(applyer.getIndirectAbleCashIncome());
                    // 更新用户间接可提现金额
                    applyer.setIndirectAbleCashIncome(String.format("%.2f",(indirectAbleCashIncome-deeIndirectAbleCashIncome)));

                  }else{
                    // 更新用户可提现金额
                     applyer.setAbleCashIncome(String.format("%.2f",ableCashIncome-Double.valueOf(axWithdrawal1.getAmout())));
                     // 插入明细
                     axAccountChangeRecord.setChangeSource(changeSouceType.拍品券提现.getCode());
                     axAccountChangeRecord.setChangeSourceName(changeSouceType.拍品券提现.name());
                     axAccountChangeRecord.setChangeAmount("-"+axWithdrawal1.getAmout());
                     axAccountChangeRecordService.insertAxAccountChangeRecord(axAccountChangeRecord);
                  }
            }

            userService.updateUser(applyer);
            axWithdrawal.setPayer(SecurityUtils.getUserId()+"");
            axWithdrawal.setAccountDate(new Date());

        }else{
            axWithdrawal.setAuditor(SecurityUtils.getUserId()+"");
            axWithdrawal.setAuditDate(new Date());
        }

        return axWithdrawalMapper.updateAxWithdrawal(axWithdrawal);
    }

    /**
     * 批量删除提现记录
     * 
     * @param ids 需要删除的提现记录主键
     * @return 结果
     */
    @Override
    public int deleteAxWithdrawalByIds(Long[] ids)
    {
        return axWithdrawalMapper.deleteAxWithdrawalByIds(ids);
    }

    /**
     * 删除提现记录信息
     * 
     * @param id 提现记录主键
     * @return 结果
     */
    @Override
    public int deleteAxWithdrawalById(Long id)
    {
        return axWithdrawalMapper.deleteAxWithdrawalById(id);
    }
}
